package top.kaoshanji.p1ch02b;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 代码清单 p1ch02b-06：被代理的接口中包含声明类型相同的方法的示例(2.3.1节)
 * author kaoshanji
 * ^_^
 * create time 2024/12/23 20:32
 */
public class MultipleInterfacesProxy {

    private static final Logger logger = LogManager.getLogger(MultipleInterfacesProxy.class);

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        logger.info("...代码清单 p1ch02b-06：被代理的接口中包含声明类型相同的方法的示例(2.3.1节)...");

        List<String> receiverObj = new ArrayList<>();
        ClassLoader cl = MultipleInterfacesProxy.class.getClassLoader();
        LoggingInvocationHandler handler = new LoggingInvocationHandler(receiverObj);

        Class<?> proxyClass = Proxy.getProxyClass(cl, new Class<?>[]{List.class, Set.class});
        Object proxy = proxyClass.getConstructor(new Class[]{InvocationHandler.class}).newInstance(new Object[]{handler});

        List list = (List) proxy;
        list.add("Hello");

        Set set = (Set) proxy;
        set.add("World");

    }

}
